local AudioFade = class("AudioFade",function() 
	return display.newNode()
end)

function AudioFade:ctor(audioId,duration,from,to,callback)
	self.duration = assert(duration)
	self.time = 0
	self.from = from
	self.to = to
	self.audioId = assert(audioId)
	self.callback = callback

	AM.setVolume(audioId,from)

	self:scheduleUpdate(handler(self,AudioFade.step))
end

function AudioFade:onCompleted()
	if self.callback then
		self.callback(self.audioId)
		self.callback=nil
	end
	local actions = {cc.DelayTime:create(0.1),cc.RemoveSelf:create()}
	self:runAction(cc.Sequence:create(actions))
	self.time=nil
end

function AudioFade:step(dt)
	if not self.time then
		return 
	end
	if self.time <= self.duration then
		self.time = self.time + dt
		local from = self.from
		local to = self.to
		local p = self.time/self.duration
		local volume = math.clamp(from + (to-from)*p,0,1)
		AM.setVolume(self.audioId,volume)
	else
		AM.setVolume(self.audioId,self.to)
		self:onCompleted()
	end
end

return AudioFade